
#include <cassert>
#include "node.h"



node* copySubtree(node* root)
{
   node* tmp = NULL;
   if (root != NULL)
   {
       tmp = new node(root);
       tmp->setLeft(copySubtree(root->getLeft()));
       tmp->setRight(copySubtree(root->getRight()));
   }
   return tmp;
}

bool node::evaluatesLeft(record* theRecord)
{
    if (field == 0 || field > 3)
        return theRecord->getFieldValue(field) <= nValue;
    else
        return (values.find((int) theRecord->getFieldValue(field)) != values.end());
}

int node::evaluateTestRecord(record* theRecord)
{
    if (evaluatesLeft(theRecord))
    {
        if (left != NULL)
            return left->evaluateTestRecord(theRecord);
        else
            return getLEWinner();
    }      
    else
    {
        if (right != NULL)
            return right->evaluateTestRecord(theRecord);
        else
        {
            return getGTWinner();
        }
    }
}

int node::getLEWinner()
{
    int best = 0;
    double value = countLE[0];
    for (int i = 1; i < 5; i++)
    {
        if (countLE[i] > value)
        {
            best = i;
            value = countLE[i];
        }
    }
    return best;
}

int node::getGTWinner()
{
    int best = 0;
    double value = countGT[0];
    for (int i = 1; i < 5; i++)
    {
        if (countGT[i] > value)
        {
            best = i;
            value = countGT[i];
        }
    }
    return best;
}  


void node::processTrainingRecord(record* theRecord)
{
    if (evaluatesLeft(theRecord))
    {
        if (left != NULL)
            left->processTrainingRecord(theRecord);
        
        countLE[theRecord->getResult()]++;
        countLESum++;
    }
    else
    {
        if (right != NULL)
            right->processTrainingRecord(theRecord);

        countGT[theRecord->getResult()]++;
        countGTSum++;
    }
}
